package com.xindaoapp.happypet.service;

import java.io.File;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.MainActivity;

/**
 * ============================================================
 * 
 * 版权 : 新道APP (c) 2014
 * 
 * 作者 : 贺奕凯
 * 
 * 版本 : 1.0
 * 
 * 创建日期 : 2014-6-23 上午11:56:24
 * 
 * 描述 : 更新服务
 * 
 * 修订历史 :
 * 
 * ============================================================
 **/
public class UpdateService extends Service {

    private String app_name;
    private String down_url;
    private String cachePath;
    private NotificationManager notificationManager;
    private Notification notification;
    private Intent updateIntent;
    private PendingIntent pendingIntent;
    private final int notification_id = 0;
    private RemoteViews contentView;
    int updateCount = 0;// 已经上传的文件大小
    private static final int TIMEOUT = 10 * 1000;// 超时
    final Message message = new Message();
    private static final int DOWN_OK = 1;
    private static final int DOWN_ERROR = 0;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        app_name = intent.getStringExtra("app_name");
        down_url = intent.getStringExtra("down_url");
        cachePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/testapp.apk";

        File file = new File(cachePath);
        if (file.exists()) {
            file.delete();
        }
        createNotification();
        Update();
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 更新方法
     */
    private void Update() {
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case DOWN_OK:
                        // 下载完成，点击安装
                        Uri uri = Uri.fromFile(new File(cachePath));
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setDataAndType(uri, "application/vnd.android.package-archive");

                        pendingIntent = PendingIntent.getActivity(UpdateService.this, 0, intent, 0);

                        notification.setLatestEventInfo(UpdateService.this, app_name, "下载成功，点击安装",
                                pendingIntent);

                        notificationManager.notify(notification_id, notification);

                        stopService(updateIntent);
                        break;
                    case DOWN_ERROR:
                        notification.setLatestEventInfo(UpdateService.this, app_name, "下载失败",
                                pendingIntent);
                        break;

                    default:
                        stopService(updateIntent);
                        break;
                }
            }
        };

        HttpUtils http = new HttpUtils();
        HttpHandler handler2 =
                http.download(down_url, cachePath, true, true, new RequestCallBack<File>() {

                    @Override
                    public void onStart() {
                        super.onStart();
                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> arg0) {
                        message.what = DOWN_OK;
                        handler.sendMessage(message);
                    }

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        message.what = DOWN_ERROR;
                        handler.sendMessage(message);
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        super.onLoading(total, current, isUploading);
                        // 改变通知栏
                        contentView.setTextViewText(R.id.notificationTitle, "正在下载...");
                        contentView.setTextViewText(R.id.notificationPercent, (current * 100
                                / total * 100)
                                / 100 + "%");
                        contentView.setProgressBar(R.id.notificationProgress, 100, (int) ((current
                                * 100 / total * 100) / 100), false);
                        // show_view
                        notificationManager.notify(notification_id, notification);
                    }

                });
    }

    private void createNotification() {
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notification = new Notification();
        notification.icon = R.drawable.icon;
        // 这个参数是通知提示闪出来的值.
        notification.tickerText = "开始下载";
        updateIntent = new Intent(this, MainActivity.class);
        pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, updateIntent, 0);
        // 这里面的参数是通知栏view显示的内容
        notification.setLatestEventInfo(getBaseContext(), app_name, "下载:0%", pendingIntent);

        contentView = new RemoteViews(getPackageName(), R.layout.notification_item);

        notification.contentView = contentView;
        updateIntent = new Intent(this, MainActivity.class);
        updateIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        pendingIntent = pendingIntent.getActivity(this, 0, updateIntent, 0);

        notification.contentIntent = pendingIntent;

        notificationManager.notify(notification_id, notification);
    }


}
